#!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1-or-later

import logging
import sys
from pathlib import Path

from mkosi.initrd import KernelInstallContext
from mkosi.log import log_setup
from mkosi.run import run, uncaught_exception_handler
from mkosi.util import PathString


@uncaught_exception_handler()
def main() -> None:
    context = KernelInstallContext.parse(
        name="51-mkosi-addon.install",
        description="kernel-install plugin to build local addon for initrd/cmdline",
    )

    log_setup(default_log_level="info" if context.verbose else "warning")

    # No local configuration? Then nothing to do
    if not Path("/etc/mkosi-addon").exists() and not Path("/run/mkosi-addon").exists():
        logging.info("No local configuration defined, skipping mkosi-addon")
        return

    if context.command != "add" or context.layout != "uki":
        logging.info("Not an UKI layout 'add' step, skipping mkosi-addon")
        return

    if context.image_type != "uki":
        logging.info("Provided kernel image is not a unified kernel image, skipping mkosi-addon")
        return

    cmdline: list[PathString] = [
        "mkosi-addon",
        "--output", "mkosi-local.addon.efi",
        "--output-dir", context.staging_area / "uki.efi.extra.d",
    ]  # fmt: skip

    if context.verbose:
        cmdline += ["--debug"]

    logging.info("Building mkosi-local.addon.efi")

    run(cmdline, stdin=sys.stdin, stdout=sys.stdout)


if __name__ == "__main__":
    main()
